import tool from '@/utils/tool';

class CacheUtil {
  cacheList = {};

  // 页面缓存
  update(name, value, expire) {
    let cached = this.get(name);
    let cache = {
      value,
    };
    // 如果设置持久缓存，并且设置过生存时间，清空
    if ((!expire || expire < 0) && cached && cached.timeout) {
      clearTimeout(cached.timeout);
    }
    if (expire > 0) {
      if (cached && cached.timeout) {
        cache.timeout = cached.timeout;
      } else {
        cache.timeout = setTimeout(() => {
          this.del(name);
        }, expire * 1000);
      }
    }
    this.cacheList[name] = cache;
  }

  get(name) {
    return tool.jsonCopy(this.cacheList[name]);
  }

  getValue(name) {
    let cache = this.get(name) || {};
    return cache.value;
  }

  del(name) {
    clearTimeout(this.cacheList[name].timeout);
    delete this.cacheList[name];
  }

  fuzzyClean(key) {
    let k = key.toLowerCase();
    Object.keys(this.cacheList).forEach((i) => {
      if (i.toLowerCase().indexOf(k) >= 0) {
        this.del(i);
      }
    });
  }

  clean() {
    Object.keys(this.cacheList).forEach((i) => {
      this.del(i);
    });
  }

  addLocalStorage(k, v) {
    if (typeof v === 'object') {
      localStorage.setItem(k, JSON.stringify[v]);
    } else {
      localStorage.setItem(k, v);
    }
  }

  getLocalStorage(k) {
    let _v = localStorage.getItem(k);
    if (!_v) {
      return;
    }
    let v = _v;
    try {
      v = JSON.parse(_v);
      return v;
    } catch (e) {
      return _v;
    }
  }
}

export default new CacheUtil();
